﻿Imports System
Imports IDServer
Imports System.Threading.Thread
Imports System.IO
Imports System.String
Imports Microsoft.VisualBasic
Imports System.Data
Imports System.Data.Sql
Imports System.Data.SqlClient
Imports System.Runtime.InteropServices

Public Class Frm_SelectGoods
    Implements IDServer.IDServer.IDServer

    Public ActionHelp As IDServer.IDServer.ActionBtn = IDServer.IDServer.ActionBtn.ActionHelp
    Private mDataset As DataSet
    Private m_Ds As DataSet
    Private FrmMain As New Frm_MainForm
    Public Fields, strFileName As String
    Private SelectNode As TreeNode
    Private selectObj As TextBox '選中的TextBox
    Private Img As ImageList
    Private GoodsDs As DataSet
    Private WithEvents MainFrom As New Frm_MainForm
    Private WithEvents mGrid As New DataGridView

    Private Captionstr As String = "條碼^Barcode&代碼^Code&中文貨品名^Cnname&英文貨品名^Enname&顔色^Color&規格^Spec&單位^Unit&單價^Price&貨品類別^GoodsType&訂貨量^POQty"

    Private _Ds As DataSet '返回的資料集
    Private mIndex As Integer
    Private _BarCode As String
    Private _fCode As String
    Private _WhereStr As String
    Private mGoodsBarCode As String
    <DllImport("user32", EntryPoint:="AnimateWindow")> _
    Private Shared Function AnimateWindow(ByVal hwnd As IntPtr, ByVal dwTime As Integer, ByVal dwFlags As Integer) As Boolean
    End Function
    Const AW_HOR_POSITIVE As Integer = 1
    Const AW_HOR_NEGATIVE As Integer = 2
    Const AW_VER_POSITIVE As Integer = 4
    Const AW_VER_NEGATIVE As Integer = 8
    Const AW_CENTER As Integer = 16
    Const AW_HIDE As Integer = 65536
    Const AW_ACTIVATE As Integer = 131072
    Const AW_SLIDE As Integer = 262144
    Private mainMenu1 As System.Windows.Forms.MainMenu
    Private menuItem1 As System.Windows.Forms.MenuItem
    Private menuItem2 As System.Windows.Forms.MenuItem
    Const AW_BLEND As Integer = 524288


    ''' <summary>
    ''' 獲取或設置資料集（DataSet）
    ''' </summary>
    ''' <value></value>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Property Ds() As DataSet
        Get
            Return _Ds
        End Get
        Set(ByVal value As DataSet)
            _Ds = value
        End Set
    End Property

    Public Property BarCode() As String
        Get
            Return _BarCode
        End Get
        Set(ByVal value As String)
            _BarCode = value
        End Set
    End Property

    Public Property GoodsBarcode() As String
        Get
            Return mGoodsBarCode
        End Get
        Set(ByVal value As String)
            mGoodsBarCode = value
        End Set
    End Property

    Public Property Index() As Integer
        Get
            Return mIndex
        End Get
        Set(ByVal value As Integer)
            mIndex = value
        End Set
    End Property

    Public Property WhereStr() As String
        Get
            Return _WhereStr
        End Get
        Set(ByVal value As String)
            If value.Length <= 0 Then
                _WhereStr = ""
            Else
                _WhereStr = value
            End If
        End Set
    End Property

    Private Sub Frm_SelectGoods_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
        Try
            If e.KeyCode = Keys.Shift Then
                e.Handled = True
                If e.KeyCode = Keys.Enter Then
                    SendKeys.Send("+{TAB}")
                    SendKeys.Send("{F4}")
                End If
            Else
                Select Case e.KeyCode
                    Case Keys.Enter
                        e.Handled = True
                        SendKeys.Send("{TAB}")
                    Case Keys.Up
                        Me.dgrdGoods.Focus()
                    Case Keys.Down
                        Me.dgrdGoods.Focus()
                    Case Keys.Escape
                        btnCancel_Click(Nothing, Nothing)
                End Select
            End If
        Catch ex As Exception
            MsgBox("txtCode_KeyDown:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub
    Public Sub LoadData()

        Dim sql As String = "SELECT a.*,Isnull(b.goodsamount,0) AS fstoreqty FROM("
        sql = sql & "   SELECT barcode = Substring(a.barcode,2,Len(Rtrim(a.barcode)) - 2),"
        sql = sql & "   a.code,a.SupperItem,a.cnname,a.enname,color = e.colorcname,spec = j.sizesname,"
        sql = sql & "   unit = b.lista,a.price,goodstype = f.ffullname,a.poqty,ISNULL(a.FMinPOQty,0)"
        sql = sql & "   AS FMinPOQty"
        sql = sql & "   FROM    dbo.bsc_goods a"
        sql = sql & "   LEFT JOIN  (SELECT c.itemcode,d.listcode, d.lista  FROM  bsc_otherdefinea c,bsc_otherdefineb d"
        sql = sql & "   WHERE  c.itemcode = 'UnitDefin' AND c.id = d.itemno) b  ON a.unit = b.listcode "
        sql = sql & "   LEFT JOIN bsc_colordefine e ON a.color = e.colorcode"
        sql = sql & "   LEFT JOIN bsc_goodstype f ON a.goodstype = f.id"
        sql = sql & "   LEFT JOIN bsc_storehouse i ON a.storehouse = i.fcode"
        sql = sql & "   LEFT JOIN bsc_sizedefine j ON a.spec = j.sizecode  WHERE  1 = 1 AND a.status = 1"
        sql = sql & "   )"
        sql = sql & "   a  LEFT JOIN"
        sql = sql & "   ("
        sql = sql & "   SELECT m.goodsbarcode, goodsamount = Isnull(m.goodsamount,0.00) - Isnull(n.fsumcount,0.00)"
        sql = sql & "   FROM   (SELECT   STORE,  goodsbarcode, SUM(goodsamount) AS goodsamount  FROM"
        sql = sql & "   (SELECT STORE = CASE tradetype WHEN '+' THEN Isnull(a.tostore,NULL)  WHEN '-' THEN Isnull(a.fromstore,NULL) END, REPLACE(b.goodsbarcode,'*','') AS goodsbarcode,goodsamount = CASE tradetype WHEN '+' THEN b.goodsamount WHEN '-' THEN (-1) * b.goodsamount ELSE 0  END"
        sql = sql & "   FROM   stor_trademaster a"
        sql = sql & "   INNER JOIN stor_tradedetail b ON a.bonum = b.bonum"
        sql = sql & "   WHERE  bostatus = 'B') a"
        sql = sql & "   WHERE    1 = 1 GROUP BY goodsbarcode,STORE) m"
        sql = sql & "   LEFT JOIN (SELECT   shopno,REPLACE(fgoodsbarcode,'*','') AS fgoodsbarcode, SUM(fsumcount) AS fsumcount FROM     sal_saleordea a INNER JOIN dbo.sal_saleordeb b ON a.fsaleordeno = b.fsaleordeno"
        sql = sql & "   WHERE    a.fordestatus = 'B' GROUP BY fgoodsbarcode,shopno) n"
        sql = sql & "   ON m.STORE = n.shopno AND m.goodsbarcode = n.fgoodsbarcode"
        sql = sql & "   LEFT JOIN bsc_storehouse p ON m.STORE = p.fcode"
        sql = sql & "   )"
        sql = sql & "   b ON a.barcode = b.goodsbarcode"
        sql = sql & "   ORDER BY barcode"

        mDataset = New DataSet
        mDataset = ReturnDataset(sql)


    End Sub

    Private Sub Frm_SelectGoods_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Try
            Me.Cursor = Cursors.WaitCursor

            'Dim T As Threading.Thread = New Threading.Thread(AddressOf LoadData)
            'T.Start()

            '' BindGrid()
            BindDgv(Me.dgrdGoods, 1, True)
            FormatDataGridView(Me.dgrdGoods)
            With Me.dgrdGoods
                .ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize
                .AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None
                .MultiSelect = True
            End With

            FillCmb(Me.cmbSpec, "Size", True)

            If Me.txtBarcode.Text & "" <> "" Then
                Me.txtBarcode_TextChanged(sender, e)
            End If
            Me.txtEnname.Focus()
        Catch ex As Exception
            Me.Cursor = Cursors.Default
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        Finally
            Me.Cursor = Cursors.Default
        End Try
    End Sub

    Private Sub BindGrid()

        Try
            Dim mTable As New DataTable
            With mTable
                .Columns.Add("Barcode")
                .Columns.Add("Code")
                .Columns.Add("SupperItem")
                .Columns.Add("Cnname")
                .Columns.Add("Enname")
                .Columns.Add("Color")
                .Columns.Add("Spec")
                .Columns.Add("GoodsType")
                .Columns.Add("Unit")
                .Columns.Add("Price")
                .Columns.Add("POQty")

            End With
            mDataset = New DataSet
            mDataset.Tables.Add(mTable)
            Me.dgrdGoods.DataSource = mDataset.Tables(0)

            With Me.dgrdGoods
                For i As Integer = 0 To .Columns.Count - 1
                    Dim mKey As String = .Columns(i).Name
                    Dim CaptionStr As String = BindHash().Item(mKey)
                    .Columns(i).HeaderText = CaptionStr
                Next
            End With
        Catch ex As Exception
            MsgBox("BindGrid:" & ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    ''' <summary>
    ''' 綁定單元格並設定標題
    ''' </summary>
    ''' <param name="dgv">要綁定標題的DataGridView</param>
    ''' <param name="Index">序號</param>
    ''' <param name="BindHash">是否绑定到哈希表</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function BindDgv(ByVal dgv As DataGridView, ByVal Index As Integer, ByVal BindHash As Boolean)
        Try
            Dim tb As New DataTable
            Dim mTable As New DataTable
            Dim Hash As New Hashtable

            With tb
                .Columns.Add("colName")
                .Columns.Add("colCaption")
            End With

            With tb.Rows
                Select Case Index
                    Case 1
                        .Add("Barcode", "條碼")
                        .Add("Code", "代碼")
                        .Add("SupperItem", "廠商産品編號")
                        .Add("Cnname", "中文貨品名")
                        .Add("Enname", "英文貨品名")
                        .Add("Color", "顔色")
                        .Add("Spec", "規格")
                        .Add("Unit", "單位")
                        .Add("Price", "單價")
                        .Add("GoodsType", "貨品類別")
                        .Add("POQty", "訂貨量")
                        .Add("FMinPOQty", "最低採購量")
                        .Add("FStoreQty", "庫存數量")
                        .Add("KY_fAmount", "可用库存")

                End Select
            End With

            If BindHash = True Then
                With mTable
                    For I As Integer = 0 To tb.Rows.Count - 1
                        .Columns.Add(tb.Rows(I).Item(0))
                    Next
                End With

                dgv.DataSource = mTable

                With Hash
                    For I As Integer = 0 To tb.Rows.Count - 1
                        Hash.Add(tb.Rows(I).Item(0), tb.Rows(I).Item(1))
                    Next
                End With

                For I As Integer = 0 To dgv.Columns.Count - 1
                    Dim colName As String
                    colName = mTable.Columns(I).ColumnName

                    dgv.Columns(colName).HeaderText = Hash.Item(colName)
                    dgv.Columns(I).HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter
                Next

            Else
                '不绑定到哈希表
                For I As Integer = 0 To tb.Rows.Count - 1
                    dgv.Columns.Add(tb.Rows(I).Item("colName"), tb.Rows(I).Item("colCaption"))
                Next
            End If

        Catch ex As Exception
            MsgBox("BindDgv：" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Function

    Private Function BindHash() As Hashtable
        Dim mHash As New Hashtable
        With mHash
            .Add("Barcode", "貨品條碼")
            .Add("Code", "貨品編碼")
            .Add("SupperItem", "供應商産品編號")
            .Add("Cnname", "中文名稱")
            .Add("Enname", "英文名稱")
            .Add("Color", "顔色")
            .Add("Spec", "規格")
            .Add("GoodsType", "貨品類別")
        End With
        Return mHash
    End Function

    Public Function ActionAdd() As Boolean Implements IDServer.IDServer.IDServer.ActionAdd

    End Function

    Public Function ActionCancel() As Boolean Implements IDServer.IDServer.IDServer.ActionCancel

    End Function

    Public Function ActionDelete() As Boolean Implements IDServer.IDServer.IDServer.ActionDelete

    End Function

    Public Function ActionEdit() As Boolean Implements IDServer.IDServer.IDServer.ActionEdit

    End Function

    Public Function ActionExport() As Boolean Implements IDServer.IDServer.IDServer.ActionExport

    End Function

    Public Function ActionFilter() As Boolean Implements IDServer.IDServer.IDServer.ActionFilter

    End Function

    Public Function ActionGoFirst() As Boolean Implements IDServer.IDServer.IDServer.ActionGoFirst

    End Function

    Public Function ActionGoLast() As Boolean Implements IDServer.IDServer.IDServer.ActionGoLast

    End Function

    Public Function ActionGoNext() As Boolean Implements IDServer.IDServer.IDServer.ActionGoNext

    End Function

    Public Function ActionGoPrevious() As Boolean Implements IDServer.IDServer.IDServer.ActionGoPrevious

    End Function

    Public Function ActionImport() As Boolean Implements IDServer.IDServer.IDServer.ActionImport

    End Function

    Public Function ActionInitialize() As Boolean Implements IDServer.IDServer.IDServer.ActionInitialize

    End Function

    Public Function ActionPrint() As Boolean Implements IDServer.IDServer.IDServer.ActionPrint

    End Function

    Public Function ActionSave() As Boolean Implements IDServer.IDServer.IDServer.ActionSave

    End Function

    Public Function ActionSelect() As Boolean Implements IDServer.IDServer.IDServer.ActionSelect

    End Function

    Private Sub ActionFind()

        Try
            Dim Sql As String = String.Empty
            Dim sql1 As String = String.Empty

            Select Case mIndex
                Case 0

                    Sql = "SELECT barcode = Substring(a.barcode,2,Len(Rtrim(a.barcode)) - 2),"
                    Sql += " a.code,a.SupperItem,a.cnname,a.enname,color = e.colorcname,spec = j.sizesname,"
                    Sql += " unit = b.lista,a.price,goodstype = f.ffullname,a.poqty,ISNULL(a.FMinPOQty,0) AS FMinPOQty  FROM   "
                    Sql += " dbo.bsc_goods a LEFT JOIN "
                    Sql += " (SELECT c.itemcode,d.listcode,d.lista  FROM  bsc_otherdefinea c,bsc_otherdefineb d WHERE  c.itemcode = 'UnitDefin' AND c.id = d.itemno) b "
                    Sql += " ON a.unit = b.listcode "
                    Sql += " LEFT JOIN bsc_colordefine e ON a.color = e.colorcode "
                    Sql += " LEFT JOIN bsc_goodstype f ON a.goodstype = f.id  "
                    Sql += " LEFT JOIN bsc_storehouse i ON a.storehouse = i.fcode "
                    Sql += " LEFT JOIN bsc_sizedefine j ON a.spec = j.sizecode "
                    Sql += " WHERE  1 = 1 AND a.status = 1"

                Case 1, 3
                    Sql = "select distinct(replace(a.Barcode,'*','')) as Barcode,a.Code,a.SupperItem,a.Cnname,a.Enname,c.ColorSName as Color,d.SizeSName as Spec,e.fCName as GoodsType from "
                    Sql += " (select Period,StoreHouse,BarCode,Batch,StorePlace,sum(Goodsamount) as Goodsamount from V_VisualStoreQuery   group by StoreHouse,Period,barcode,Batch,StorePlace) p"
                    Sql += " inner join BSC_Goods a on p.BarCode=a.BarCode"
                    Sql += " left join BSC_ColorDefine c on a.Color=c.ColorCode "
                    Sql += " left join BSC_SizeDefine d on a.Spec=d.SizeCode"
                    Sql += " left join BSC_goodstype e on a.GoodsType=e.ID where 1=1 and a.Status=1"
                Case 2
                    Sql = "SELECT barcode = Substring(a.barcode,2,Len(Rtrim(a.barcode)) - 2),"
                    Sql = Sql & "        a.code,"
                    Sql = Sql & "        a.cnname,"
                    Sql = Sql & "        a.enname,a.SupperItem,"
                    Sql = Sql & "        color = e.colorcname,"
                    Sql = Sql & "        spec = j.sizesname,"
                    Sql = Sql & "        unit = b.lista,"
                    Sql = Sql & "        a.price,"
                    Sql = Sql & "        goodstype = f.ffullname,"
                    Sql = Sql & "        a.poqty,ISNULL(a.FMinPOQty,0) AS FMinPOQty"
                    Sql = Sql & " FROM   dbo.bsc_goods a"
                    Sql = Sql & "        LEFT JOIN (SELECT c.itemcode,"
                    Sql = Sql & "                          d.listcode,"
                    Sql = Sql & "                          d.lista"
                    Sql = Sql & "                   FROM   bsc_otherdefinea c,"
                    Sql = Sql & "                          bsc_otherdefineb d"
                    Sql = Sql & "                   WHERE  c.itemcode = 'UnitDefin'"
                    Sql = Sql & "                          AND c.id = d.itemno) b"
                    Sql = Sql & "          ON a.unit = b.listcode"
                    Sql = Sql & "        LEFT JOIN bsc_colordefine e"
                    Sql = Sql & "          ON a.color = e.colorcode"
                    Sql = Sql & "        LEFT JOIN bsc_goodstype f"
                    Sql = Sql & "          ON a.goodstype = f.id"
                    Sql = Sql & "        LEFT JOIN bsc_storehouse i"
                    Sql = Sql & "          ON a.storehouse = i.fcode"
                    Sql = Sql & "        LEFT JOIN bsc_sizedefine j"
                    Sql = Sql & "          ON a.spec = j.sizecode"
                    Sql = Sql & " WHERE  1 = 1"
                    Sql = Sql & "        AND a.status = 1 "
                    If _WhereStr.Length > 0 Then
                        Sql += " and f.ffullname like '%" & _WhereStr & "%'"
                    End If

                Case 4
                    'Sql = "SELECT barcode = Substring(a.barcode,2,Len(Rtrim(a.barcode)) - 2),"
                    'Sql += " a.code,a.SupperItem,a.cnname,a.enname,color = e.colorcname,spec = j.sizesname,"
                    'Sql += " unit = b.lista,a.price,goodstype = f.ffullname,a.poqty,ISNULL(a.FMinPOQty,0) AS FMinPOQty into #t1  FROM   "
                    'Sql += " dbo.bsc_goods a LEFT JOIN "
                    'Sql += " (SELECT c.itemcode,d.listcode,d.lista  FROM  bsc_otherdefinea c,bsc_otherdefineb d WHERE  c.itemcode = 'UnitDefin' AND c.id = d.itemno) b "
                    'Sql += " ON a.unit = b.listcode "
                    'Sql += " LEFT JOIN bsc_colordefine e ON a.color = e.colorcode "
                    'Sql += " LEFT JOIN bsc_goodstype f ON a.goodstype = f.id  "
                    'Sql += " LEFT JOIN bsc_storehouse i ON a.storehouse = i.fcode "
                    'Sql += " LEFT JOIN bsc_sizedefine j ON a.spec = j.sizecode "
                    'Sql += " WHERE  1 = 1 AND a.status = 1"

                    Sql += "SELECT barcode = Substring(a.barcode,2,Len(Rtrim(a.barcode)) - 2)," + vbNewLine
                    Sql += "a.code,a.SupperItem,a.cnname,a.enname,color = e.colorcname,spec = j.sizesname," + vbNewLine
                    Sql += "unit = b.lista,a.price,goodstype = f.ffullname,a.poqty,ISNULL(a.FMinPOQty,0)" + vbNewLine
                    sql += "AS FMinPOQty" + vbNewLine
                    Sql += "--into #t1" + vbNewLine
                    Sql += "FROM    dbo.bsc_goods a" + vbNewLine
                    Sql += "LEFT JOIN  (SELECT c.itemcode,d.listcode, d.lista  FROM  bsc_otherdefinea c,bsc_otherdefineb d" + vbNewLine
                    Sql += "WHERE  c.itemcode = 'UnitDefin' AND c.id = d.itemno) b  ON a.unit = b.listcode" + vbNewLine
                    Sql += "LEFT JOIN bsc_colordefine e ON a.color = e.colorcode" + vbNewLine
                    Sql += "LEFT JOIN bsc_goodstype f ON a.goodstype = f.id" + vbNewLine
                    Sql += "LEFT JOIN bsc_storehouse i ON a.storehouse = i.fcode" + vbNewLine
                    Sql += "LEFT JOIN bsc_sizedefine j ON a.spec = j.sizecode  WHERE  1 = 1 AND a.status = 1" + vbNewLine

            End Select

            If Me.txtBarcode.TextLength > 0 Then
                Sql += " and a.BarCode like '%" & Me.txtBarcode.Text & "%'"
            End If

            'If Me.txtCnname.TextLength > 0 Then
            '    Sql += " and a.Cnname like '%" & Me.txtCnname.Text & "%'"
            'End If

            If Me.txtEnname.TextLength > 0 Then
                Sql += " and a.Enname like '%" & Me.txtEnname.Text & "%'"
            End If

            If Me.txtCode.TextLength > 0 Then
                Sql += " and a.Code like '%" & Me.txtCode.Text & "%'"
            End If

            If Me.txtGoodsType.TextLength > 0 Then
                Sql += " and f.ffullname like '%" & Me.txtGoodsType.Text & "%'"
            End If

            If Me.txtSupperCode.Text.Length > 0 Then
                Sql += " and a.SupperItem like '%" & Me.txtSupperCode.Text & "%'"

            End If

            If mIndex = 4 Then
                'Sql += ";"

                'Sql = Sql & "SELECT m.goodsbarcode,"
                'Sql = Sql & "        goodsamount = Isnull(m.goodsamount,0.00) - Isnull(n.fsumcount,0.00)"
                'Sql = Sql & " INTO   #t2"
                'Sql = Sql & " FROM   (SELECT   STORE,"
                'Sql = Sql & "                  goodsbarcode,"
                'Sql = Sql & "                  SUM(goodsamount) AS goodsamount"
                'Sql = Sql & "         FROM     (SELECT STORE = CASE tradetype "
                'Sql = Sql & "                                    WHEN '+' THEN Isnull(a.tostore,NULL)"
                'Sql = Sql & "                                    WHEN '-' THEN Isnull(a.fromstore,NULL)"
                'Sql = Sql & "                                  END,"
                'Sql = Sql & "                          REPLACE(b.goodsbarcode,'*','') AS goodsbarcode,"
                'Sql = Sql & "                          goodsamount = CASE tradetype "
                'Sql = Sql & "                                          WHEN '+' THEN b.goodsamount"
                'Sql = Sql & "                                          WHEN '-' THEN (-1) * b.goodsamount"
                'Sql = Sql & "                                          ELSE 0"
                'Sql = Sql & "                                        END"
                'Sql = Sql & "                   FROM   stor_trademaster a"
                'Sql = Sql & "                          INNER JOIN stor_tradedetail b"
                'Sql = Sql & "                            ON a.bonum = b.bonum"
                'Sql = Sql & "                   WHERE  bostatus = 'B') a"
                'Sql = Sql & "         WHERE    1 = 1"
                'Sql = Sql & "         GROUP BY goodsbarcode,STORE) m"
                'Sql = Sql & "        LEFT JOIN (SELECT   shopno,"
                'Sql = Sql & "                            REPLACE(fgoodsbarcode,'*','') AS fgoodsbarcode,"
                'Sql = Sql & "                            SUM(fsumcount) AS fsumcount"
                'Sql = Sql & "                   FROM     sal_saleordea a"
                'Sql = Sql & "                            INNER JOIN dbo.sal_saleordeb b"
                'Sql = Sql & "                              ON a.fsaleordeno = b.fsaleordeno"
                'Sql = Sql & "                   WHERE    a.fordestatus = 'B'"
                'Sql = Sql & "                   GROUP BY fgoodsbarcode,shopno) n"
                'Sql = Sql & "          ON m.STORE = n.shopno"
                'Sql = Sql & "             AND m.goodsbarcode = n.fgoodsbarcode"
                'Sql = Sql & "        LEFT JOIN bsc_storehouse p"
                'Sql = Sql & "          ON m.STORE = p.fcode;"

                'Sql = Sql & "SELECT a.*,"
                'Sql = Sql & "        Isnull(b.goodsamount,0) AS fstoreqty"
                'Sql = Sql & " FROM   #t1 a"
                'Sql = Sql & "        LEFT JOIN #t2 b"
                'Sql = Sql & "          ON a.barcode = b.goodsbarcode    ORDER BY barcode"

                sql1 += "SELECT a.*,Isnull(h.goodsamount,0) AS fstoreqty,isnull(h.KY_fAmount,0) as KY_fAmount FROM" + vbNewLine
                sql1 += "(" + vbNewLine
                sql1 += "{0} )" + vbNewLine
                Sql1 += "a  LEFT JOIN" + vbNewLine
                sql1 += "(" + vbNewLine
                sql1 += "  select Barcode, "
                sql1 += "  Convert(Int,sum(InQty)) as InQty,"
                sql1 += "  Convert(Int,sum(OutQty)) as OutQty ,"
                sql1 += "  Convert(Int,sum(Goodsamount)) as Goodsamount,"
                sql1 += "  Convert(Int,sum(BeginQty)) as BeginQty,"
                sql1 += "  Convert(Int,sum(KY_fAmount)) as KY_fAmount from "
                sql1 += "  (  select BarCode,InQty,OutQty,Goodsamount,BeginQty,"
                sql1 += "  Convert(int,0) as KY_fAmount  from V_Storequery a  union  all   select BarCode,"
                sql1 += "  Convert(int,0) as InQty,"
                sql1 += "  Convert(int,0) as OutQty,"
                sql1 += "  Convert(int,0) as Goodsamount,"
                sql1 += "  Convert(int,0) as BeginQty,Goodsamount as KY_fAmount  from V_VisualStoreQuery a ) a  "
                sql1 += "  group by BarCode "
                sql1 += "  )h ON a.barcode = replace(h.barcode,'*','')" + vbNewLine
                sql1 += " ORDER BY h.barcode" + vbNewLine

                Sql = String.Format(sql1, Sql)
                'Sql += ";"
                'Sql += "  select storehouse,fshortname,barcode,sum(isnull(InQty,0)) as InQty,sum(isnull(OutQty,0)) as OutQty,  "
                'Sql += " sum(Goodsamout) as Goodsamount,  sum(isnull(BeginQty,0)) as BeginQty"
                'Sql += " from ("
                'Sql += " select a.storehouse,a.BarCode,isnull(a.InQty,0) as Inqty,isnull(a.OutQty,0) as OutQty,isnull(a.Goodsamount,0) as Goodsamout,isnull(a.BeginQty,0) as BeginQty, "
                'Sql += " c.fshortname  as fshortname from V_Storequery a left join bsc_storehouse c on a.storehouse=c.fcode union  all "
                'Sql += "  select e.storehouse, e.BarCode,isnull(e.InQty,0) as Inqty, isnull(e.OutQty,0) as OutQty,isnull(e.Goodsamount,0) as Goodsamout,"
                'Sql += " isnull(e.BeginQty,0) as BeginQty,d.fshortname from V_VisualStoreQuery e left join  bsc_storehouse d on e.storehouse=d.fcode"
                'Sql += " )f  group by storehouse,fshortname,BarCode "

            End If

            mDataset = ReturnDataset(Sql)

            Me.dgrdGoods.DataSource = mDataset.Tables(0)
            If Me.dgrdGoods.Rows.Count = 1 Then
                Me.dgrdGoods.Focus()
                Me.dgrdGoods.CurrentCell = Me.dgrdGoods.Rows(0).Cells(0)
                dgrdGoods_CellClick(Nothing, Nothing)
            End If
        Catch ex As Exception
            MsgBox("ActionFind" & ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Private Sub txtGoodsType_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtGoodsType.DoubleClick
        Try
            selectObj = Me.txtGoodsType

            With Me.Panel7
                .Visible = Not .Visible
                .Left = Me.txtGoodsType.Left
                .Top = Me.txtGoodsType.Top - 8
                '.Width = 300
                .Height = 300
                .AutoScroll = True
            End With

            If Me.Panel7.Visible = True Then
                If Me.TVGoodsType.Nodes.Count <= 0 Then
                    LoadGoodsType(Me.TVGoodsType)
                    Me.TVGoodsType.ExpandAll()
                End If

                If Me.txtGoodsType.Text.Length > 0 Then
                    Dim strGoodsType As String = Me.txtGoodsType.Text
                    SelectTreeView(Me.TVGoodsType, strGoodsType)
                End If
            End If


        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub txtBarcode_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtBarcode.KeyDown, txtCode.KeyDown, _
                                    txtEnname.KeyDown, _
                                    cmbSpec.KeyDown, txtGoodsType.KeyDown
        Try
            If e.KeyCode = Keys.Enter Then
                Select Case e.KeyCode
                    Case Keys.Enter
                        e.Handled = True
                        Me.BtnFind_Click(sender, e)
                    Case Keys.Escape
                        Me.btnCancel_Click(sender, e)
                End Select
            End If
        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub txtBarcode_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtBarcode.TextChanged, _
               txtCode.TextChanged, txtEnname.TextChanged, cmbSpec.TextChanged, txtGoodsType.TextChanged, txtSupperCode.TextChanged
        If Me.txtBarcode.Text.Length >= 7 And Me.txtEnname.Text.Length <= 8 Then
            Me.BtnFind_Click(sender, e)
        End If
    End Sub

    Private Sub BtnFind_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnFind.Click
        Try
            ActionFind()
            'Dim Newdatatable As DataTable = New DataTable
            'Dim Row() As DataRow = mDataset.Tables(0).Select("barcode like '%" & Me.txtBarcode.Text.Trim & "%' and enname like '%" & Me.txtEnname.Text & "%' and  code like '%" & Me.txtCode.Text & "%'  and goodstype  like '%" & Me.txtGoodsType.Text & "%' and  SupperItem like '%" & Me.txtSupperCode.Text & "%'")
            'If Row.Length > 0 Then
            '    Dim mtable As DataTable = mDataset.Tables(0).Copy
            '    For i As Integer = 0 To Row.Length - 1
            '        mDataset.Tables(0).ImportRow(Row(i))
            '    Next
            '    mDataset.AcceptChanges()
            '    Newdatatable = mDataset.Tables(0).Copy
            '    Me.dgrdGoods.DataSource = Newdatatable
            '    If Me.dgrdGoods.Rows.Count = 1 Then
            '        Me.dgrdGoods.Focus()
            '        Me.dgrdGoods.CurrentCell = Me.dgrdGoods.Rows(0).Cells(0)
            '        dgrdGoods_CellClick(Nothing, Nothing)
            '    End If
            'End If
        Catch ex As Exception
            Me.Cursor = Cursors.Default
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        Finally
            Me.Cursor = Cursors.Default
        End Try

    End Sub

    Private Sub btnOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOK.Click
        Try
            If Me.dgrdGoods.SelectedRows.Count > 0 Then

                PubGoodsDataSet.Tables.Clear()

                Dim tb As New DataTable
                Dim FirstSelectRow, LastSelectRow, intSelectRows As Integer
                Dim intRows() As Integer

                '選擇的第1行

                FirstSelectRow = Me.dgrdGoods.SelectedRows(0).Index

                '選擇的最後一行

                If Me.dgrdGoods.SelectedRows.Count > 1 Then
                    LastSelectRow = Me.dgrdGoods.SelectedRows(Me.dgrdGoods.SelectedRows.Count - 1).Index
                End If


                intSelectRows = Me.dgrdGoods.SelectedRows.Count
                ReDim intRows(intSelectRows - 1)
                For i As Integer = 0 To intSelectRows - 1
                    intRows(i) = Me.dgrdGoods.SelectedRows(i).Index
                Next

                For i As Integer = intRows.Length - 1 To 0 Step -1
                    _BarCode += Me.dgrdGoods.Rows(intRows(i)).Cells("BarCode").Value & "^"
                Next

                tb = mDataset.Tables(0).Copy
                tb.Rows.Clear()

                PubGoodsDataSet.Tables.Add(tb)

                '順向選擇
                If FirstSelectRow > LastSelectRow Then
                    For J As Integer = intRows.LongLength - 1 To 0 Step -1
                        'For Each row As DataGridViewRow In Me.dgrdGoods.Rows

                        Dim mRow As DataRow
                        mRow = tb.NewRow()

                        For Each col As DataColumn In tb.Columns
                            mRow(col) = Me.dgrdGoods.Rows(intRows(J)).Cells(col.ColumnName).Value
                        Next

                        tb.Rows.Add(mRow)
                        PubGoodsDataSet.AcceptChanges()

                        'Next

                    Next
                Else
                    '反向選擇
                    For J As Integer = 0 To intRows.LongLength - 1
                        'For Each row As DataGridViewRow In Me.dgrdGoods.Rows

                        Dim mRow As DataRow
                        mRow = tb.NewRow()

                        For Each col As DataColumn In tb.Columns
                            mRow(col) = Me.dgrdGoods.Rows(intRows(J)).Cells(col.ColumnName).Value
                        Next

                        tb.Rows.Add(mRow)
                        PubGoodsDataSet.AcceptChanges()

                    Next

                End If

            End If

            Me.Ds = PubGoodsDataSet

            Me.DialogResult = Windows.Forms.DialogResult.OK
        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        'AnimateWindow(Me.Handle, 1000, AW_SLIDE Or AW_HIDE Or AW_VER_NEGATIVE)
        Me.DialogResult = Windows.Forms.DialogResult.Cancel
    End Sub

    Private Sub dgrdGoods_CellClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgrdGoods.CellClick
    End Sub

    Private Sub ShowPO()
        Try
            Dim sql = ""
            Dim Dset As DataSet
            Dim CurrentBarcode As String = Me.dgrdGoods.CurrentRow.Cells("Barcode").Value
            If CurrentBarcode.Length <= 0 Then
                Exit Sub
            End If
            sql = " select  a.Qty as PO, Convert(varchar(10),b.DeliveryDate,120) as DeliverDate "
            sql += "from Pur_POB a left join Pur_POA b  on a.num = b.num "
            sql += " where Convert(varchar(10),b.DeliveryDate,120)>= Convert(varchar(10),getdate(),120) and b.BillstatusID = 'B' and "
            sql += " REPLACE(barcode,'*','') = '" & CurrentBarcode & "'"
            Dset = Exec(sql, E_ExecType.DataSet)
            Me.DGVPo.DataSource = Dset.Tables(0)
        Catch ex As Exception
            MessageBox.Show(ex.ToString, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
        End Try
    End Sub
    Private Sub CountQty()
        Try
            Dim Dset As DataSet
            Dim sql As String = ""
            Dim CurrentBarcode As String = Me.dgrdGoods.CurrentRow.Cells("Barcode").Value
            sql = "select distinct isnull(sum(a.fSumCount),'0') as fSumCount From sal_saleordeB  a left join sal_saleordeA b "
            sql += " on a.fSaleOrdeNo = b.fSaleOrdeNo  where  b.fOrdeStatus= 'B' "

            '修改代碼，提高效率，由於sal_fSaleOrdeB表中的記錄上百萬，直接使用Replace函數來查詢，需要3秒鐘左右，不使用Replace函數則不到一秒鐘就可以找到
            'sql += " and REPLACE(fGoodsBarCode,'*','') = '" & CurrentBarcode & "'"
            sql += " and fGoodsBarCode in( '" & CurrentBarcode & "','*" & CurrentBarcode & "*')"
            Dset = ReturnDataset(sql)
            Me.LBLOrdeQty.Text = ""
            Me.LBLOrdeQty.Text = Dset.Tables(0).Rows(0)(0).ToString
        Catch ex As Exception
            MessageBox.Show("Initialize:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK)
        End Try
    End Sub

    Private Sub LoadFirstTree(ByVal Barcode As String, Optional ByVal Index As Integer = 0)

        Try
            Me.TreeView1.Nodes.Clear()
            Dim mNode As New TreeNode
            mNode.Tag = "All"
            mNode.Text = "全部"
            Me.TreeView1.Nodes.Add(mNode)
            LoadSecondTree(mNode, Barcode, Index)
            Me.TreeView1.ExpandAll()
            Me.TreeView1.LineColor = Color.Blue
        Catch ex As Exception
            MsgBox("LoadFirstTree:" & ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Private Sub LoadSecondTree(ByVal ParentNode As TreeNode, ByVal Barcode As String, ByVal Index As Integer)

        Try
            Dim sql As String = ""
            Dim Node As TreeNode
            ''Dim nNode As TreeNode
            Dim mHash As New Hashtable
            Dim m_DS As New DataSet
            Select Case Index
                'Case 0
                '    sql = "select p.fShortName,m.Store,m.GoodsBarcode,Goodsamount=isnull(m.Goodsamount,0.00)-isnull(n.fSumCount,0.00) from "
                '    sql += "(select Store,GoodsBarCode,sum(Goodsamount) as Goodsamount from "
                '    sql += "(select Store=case tradetype when '+' then isnull(a.ToStore,null) when '-' then isnull(a.FromStore,null) end,"
                '    sql += "replace(b.GoodsBarCode,'*','') as GoodsBarcode, goodsamount=case tradetype when '+' then b.Goodsamount when '-' then (-1)* b.Goodsamount else 0 end "
                '    sql += "from Stor_TradeMaster a inner join Stor_TradeDetail b on a.bonum=b.bonum where BoStatus='B') a where 1=1 group by GoodsBarCode,Store) m left join "
                '    sql += "(select ShopNo,Replace(fGoodsBarCode,'*','') as fGoodsBarCode,sum(fSumCount) as fSumCount from Sal_SaleOrdeA a inner join dbo.Sal_SaleOrdeB b on a.fSaleOrdeNo=b.fSaleOrdeNo where a.fOrdeStatus='B' group by fGoodsBarcode,ShopNo) n "
                '    sql += "on m.Store=n.ShopNo and m.GoodsBarCode=n.fGoodsBarCode left join BSC_StoreHouse p on m.Store=p.fCode where GoodsBarcode='" & Barcode & "'"
                Case 1
                    sql = "select a.*,b.fShortName,Batch1='批次',StorePlace1='庫位',Goodsamount1='可用庫存',c.fVirtual  from  (select Period,StoreHouse,replace(BarCode,'*','') as BarCode,Batch,StorePlace,sum(Goodsamount) as Goodsamount from V_VisualStoreQuery group by StoreHouse,Period,barcode,Batch,StorePlace) a "
                    sql += " inner join BSC_StoreHouse b on a.StoreHouse=b.fCode left join BSC_Storage c on a.StorePlace=c.fStorageId where StoreHouse='" & PubCompanyCode & "' and c.fCode='" & PubCompanyCode & "' and isnull(a.Goodsamount,0.00)>0 and BarCode='" & Barcode & "' order by substring(Batch,4,3),substring(Batch,1,3)"
                Case 0, 2, 4
                    sql = "select  c.storehouse,c.Barcode,   Convert(Int,sum(c.InQty)) as InQty,  Convert(Int,sum(c.OutQty)) as OutQty , "
                    sql += "Convert(Int,sum(Goodsamount)) as Goodsamount,  "
                    sql += "Convert(Int,sum(BeginQty)) as BeginQty,  "
                    sql += "Convert(Int,sum(KY_fAmount)) as KY_fAmount into #t1 from   "
                    sql += "(select storehouse, BarCode,InQty,OutQty,Goodsamount,BeginQty,  Convert(int,0) as KY_fAmount  from V_Storequery a  union  all   "
                    sql += "select storehouse,BarCode,  Convert(int,0) as InQty,  Convert(int,0) as OutQty,  Convert(int,0) as Goodsamount,  Convert(int,0) as BeginQty,Goodsamount as KY_fAmount  from V_VisualStoreQuery a ) c  "
                    sql += "where barcode='*" & Barcode & "*'"
                    sql += "group by storehouse,BarCode "
                    sql += "ORDER BY h.barcode;"
                    sql += "select a.*,b.fshortname from #t1 a left join bsc_storehouse b on a.storehouse=b.fcode;"
                    sql += "drop table #t1;"

                Case 3
                    sql = "select a.*,b.fShortName,Batch1='批次',StorePlace1='庫位',Goodsamount1='可用庫存',c.fVirtual  from  (select Period,StoreHouse,replace(BarCode,'*','') as BarCode,Batch,StorePlace,sum(Goodsamount) as Goodsamount from V_VisualStoreQuery group by StoreHouse,Period,barcode,Batch,StorePlace) a "
                    sql += " inner join BSC_StoreHouse b on a.StoreHouse=b.fCode left join BSC_Storage c on a.StorePlace=c.fStorageId where StoreHouse='" & PubCompanyCode & "' and isnull(a.Goodsamount,0.00)>0 and BarCode='" & Barcode & "' order by substring(Batch,4,3),substring(Batch,1,3)"

            End Select
            m_DS = ReturnDataset(sql)


            If m_DS.Tables(0).Rows.Count > 0 Then
                Select Case Index
                    Case 0
                        For Each mRow As DataRow In m_DS.Tables(0).Rows
                            Node = New TreeNode
                            Node.Tag = mRow("Goodsamount")
                            Node.Text = mRow("fShortName") & "[" & mRow("Goodsamount") & "]"
                            If Not ParentNode.Nodes.Contains(Node) Then
                                ParentNode.Nodes.Add(Node)
                            End If
                        Next
                    Case 1
                        For Each mRow As DataRow In m_DS.Tables(0).Rows

                            If mRow("fVirtual") & "" = "1" Then

                                Node = New TreeNode
                                Node.Tag = mRow("StoreHouse") & ""
                                Node.Text = "壞貨倉" & "[" & mRow("StoreHouse") & "]"
                                ParentNode.Nodes.Add(Node)

                                Dim BatchNode As TreeNode

                                BatchNode = New TreeNode
                                BatchNode.Tag = mRow("Batch") & ""
                                BatchNode.Text = mRow("Batch1") & "[" & mRow("Batch") & "]"
                                Node.Nodes.Add(BatchNode)

                                If Convert.ToDouble(mRow("Goodsamount")) <= 0 Then
                                Else
                                    Dim GoodsamountNode As New TreeNode
                                    GoodsamountNode.Tag = mRow("Goodsamount")
                                    GoodsamountNode.Text = mRow("Goodsamount1") & "[" & mRow("Goodsamount") & "]"
                                    BatchNode.Nodes.Add(GoodsamountNode)
                                End If
                            Else
                                If Not mHash.ContainsKey(mRow("StoreHouse") & "") Then
                                    Node = New TreeNode
                                    Node.Tag = mRow("StoreHouse") & ""
                                    Node.Text = mRow("fShortName") & "[" & mRow("StoreHouse") & "]"
                                    mHash.Add(mRow("StoreHouse") & "", mRow("fShortName") & "")
                                    ParentNode.Nodes.Add(Node)
                                End If

                                Dim BatchNode As TreeNode

                                If Not mHash.ContainsKey(mRow("Batch") & "") Then
                                    BatchNode = New TreeNode
                                    BatchNode.Tag = mRow("Batch") & ""
                                    BatchNode.Text = mRow("Batch1") & "[" & mRow("Batch") & "]"
                                    mHash.Add(mRow("Batch") & "", mRow("Batch1") & "")
                                    Node.Nodes.Add(BatchNode)
                                End If

                                Dim StorePlaceNode As TreeNode

                                If Convert.ToDouble(mRow("Goodsamount")) <= 0 Then
                                Else
                                    If Not mHash.ContainsKey(mRow("StorePlace") & "") Then
                                        StorePlaceNode = New TreeNode
                                        StorePlaceNode.Tag = mRow("StorePlace")
                                        StorePlaceNode.Text = mRow("StorePlace1") & "[" & mRow("StorePlace") & "]"
                                        mHash.Add(mRow("StorePlace") & "", mRow("StorePlace1") & "")
                                        BatchNode.Nodes.Add(StorePlaceNode)
                                    End If

                                    Dim GoodsamountNode As New TreeNode
                                    GoodsamountNode.Tag = mRow("Goodsamount")
                                    GoodsamountNode.Text = mRow("Goodsamount1") & "[" & mRow("Goodsamount") & "]"
                                    StorePlaceNode.Nodes.Add(GoodsamountNode)
                                End If
                            End If
                        Next
                    Case 2, 4
                        For Each mRow As DataRow In m_DS.Tables(0).Rows
                            Node = New TreeNode
                            Node.Tag = mRow("StoreHouse") & ""
                            Node.Text = mRow("fShortName") & "[" & mRow("StoreHouse") & "]"
                            ParentNode.Nodes.Add(Node)

                            Dim GoodsamountNode As New TreeNode
                            GoodsamountNode.Tag = mRow("Goodsamount")
                            GoodsamountNode.Text = mRow("Goodsamount") & "----【" & mRow("KY_fAmount") & "】"
                            Node.Nodes.Add(GoodsamountNode)
                        Next
                    Case 3
                        For Each mRow As DataRow In m_DS.Tables(0).Rows

                            If mRow("fVirtual") & "" = "1" Then

                                Node = New TreeNode
                                Node.Tag = mRow("StoreHouse") & ""
                                Node.Text = "壞貨倉" & "[" & mRow("StoreHouse") & "]"
                                ParentNode.Nodes.Add(Node)

                                Dim BatchNode As TreeNode

                                BatchNode = New TreeNode
                                BatchNode.Tag = mRow("Batch") & ""
                                BatchNode.Text = mRow("Batch1") & "[" & mRow("Batch") & "]"
                                Node.Nodes.Add(BatchNode)

                                If Convert.ToDouble(mRow("Goodsamount")) <= 0 Then
                                Else
                                    Dim GoodsamountNode As New TreeNode
                                    GoodsamountNode.Tag = mRow("Goodsamount")
                                    GoodsamountNode.Text = mRow("Goodsamount1") & "[" & mRow("Goodsamount") & "]"
                                    BatchNode.Nodes.Add(GoodsamountNode)
                                End If
                            Else
                                If Not mHash.ContainsKey(mRow("StoreHouse") & "") Then
                                    Node = New TreeNode
                                    Node.Tag = mRow("StoreHouse") & ""
                                    Node.Text = mRow("fShortName") & "[" & mRow("StoreHouse") & "]"
                                    mHash.Add(mRow("StoreHouse") & "", mRow("fShortName") & "")
                                    ParentNode.Nodes.Add(Node)
                                End If

                                Dim BatchNode As TreeNode

                                If Not mHash.ContainsKey(mRow("Batch") & "") Then
                                    BatchNode = New TreeNode
                                    BatchNode.Tag = mRow("Batch") & ""
                                    BatchNode.Text = mRow("Batch1") & "[" & mRow("Batch") & "]"
                                    mHash.Add(mRow("Batch") & "", mRow("Batch1") & "")
                                    Node.Nodes.Add(BatchNode)
                                End If

                                Dim StorePlaceNode As TreeNode

                                If Convert.ToDouble(mRow("Goodsamount")) <= 0 Then
                                Else
                                    If Not mHash.ContainsKey(mRow("StorePlace") & "") Then
                                        StorePlaceNode = New TreeNode
                                        StorePlaceNode.Tag = mRow("StorePlace")
                                        StorePlaceNode.Text = mRow("StorePlace1") & "[" & mRow("StorePlace") & "]"
                                        mHash.Add(mRow("StorePlace") & "", mRow("StorePlace1") & "")
                                        BatchNode.Nodes.Add(StorePlaceNode)
                                    End If

                                    Dim GoodsamountNode As New TreeNode
                                    GoodsamountNode.Tag = mRow("Goodsamount")
                                    GoodsamountNode.Text = mRow("Goodsamount1") & "[" & mRow("Goodsamount") & "]"
                                    StorePlaceNode.Nodes.Add(GoodsamountNode)
                                End If
                            End If
                        Next
                End Select

            End If
        Catch ex As Exception
            MsgBox("LoadSecondTree:" & ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Private Sub dgrdGoods_CellDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgrdGoods.CellDoubleClick
        Me.btnOK_Click(sender, e)
    End Sub

    Private Sub dgrdGoods_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles dgrdGoods.KeyDown
        Try
            If e.KeyCode = Keys.Enter Then
                Select Case e.KeyCode
                    Case Keys.Enter
                        e.Handled = True
                        Me.btnOK_Click(sender, e)
                    Case Keys.Escape
                        Me.btnCancel_Click(sender, e)

                End Select
            End If
            Select Case e.KeyCode
                Case Keys.Up
                    dgrdGoods_CellClick(Nothing, Nothing)
                Case Keys.Down
                    dgrdGoods_CellClick(Nothing, Nothing)
            End Select
        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Private Sub LoadGoodsType(ByVal TV As TreeView)

        Try
            Dim Node As New TreeNode
            Img = New ImageList()
            Dim Company As String = Application.StartupPath & "\pic\35FLOPPY.BMP"
            Dim bumen As String = Application.StartupPath & "\pic\CLSDFOLD.BMP"
            Dim gangwei As String = Application.StartupPath & "\pic\OPENFOLD.BMP"
            Dim Image As Image = Nothing
            Img.Images.Add(Drawing.Image.FromFile(Company))
            Img.Images.Add(Drawing.Image.FromFile(bumen))
            Img.Images.Add(Drawing.Image.FromFile(gangwei))
            TV.ImageList = Img
            Node.Nodes.Clear()
            Node.Tag = "All"
            Node.Text = "全部"
            Node.ImageIndex = 0
            TV.Nodes.Add(Node)
            Dim sql As String = ""
            sql = "select * from dbo.BSC_GoodsType"
            GoodsDs = New DataSet
            GoodsDs = ReturnDataset(sql)
            LoadSecondTree1(Node, 0)
            SelectNode = Node
            Node.Expand()
        Catch ex As Exception
            MsgBox("LoadGoodsType:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub LoadSecondTree1(ByVal TreeNode As TreeNode, ByVal ParentID As Integer)
        Try
            If GoodsDs Is Nothing Then Exit Sub
            Dim Rows() As DataRow = GoodsDs.Tables(0).Select("fParentId=" & ParentID)
            Dim Define As Int16 = 0
            For Each mRow As DataRow In Rows
                Dim mNode As New TreeNode
                Define = mRow("fDefine")
                If TreeNode Is Nothing Then
                    mNode.Tag = mRow("ID") & "^" & mRow("fDefine")
                    mNode.Text = "(" & mRow("fCode") & ")" & mRow("fCName")
                    mNode.ImageIndex = 1
                    mNode.SelectedImageIndex = 2
                    TreeNode.Nodes.Add(mNode)
                    mNode.Expand()
                    LoadSecondTree1(mNode, mRow("ID"))
                Else
                    mNode.Tag = mRow("ID") & "^" & mRow("fDefine")
                    mNode.Text = "(" & mRow("fCode") & ")" & mRow("fCName")
                    mNode.ImageIndex = 1
                    mNode.SelectedImageIndex = 2
                    TreeNode.Nodes.Add(mNode)
                    mNode.Expand()
                    LoadSecondTree1(mNode, mRow("ID"))
                End If
            Next
        Catch ex As Exception
            MsgBox("LoadSecondTree:" + ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    ''' <summary>
    ''' 選擇TreeView的某個TreeNode
    ''' </summary>
    ''' <param name="aTreeView">需查詢的TreeView</param>
    ''' <param name="strFullPath">需查詢的TreeNode的FullPath</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function SelectTreeView(ByVal aTreeView As TreeView, ByVal strFullPath As String) As Boolean
        Dim n As TreeNode
        Dim bFind As Boolean = False
        For Each n In aTreeView.Nodes
            bFind = FindSecondNode(aTreeView, n, strFullPath)
            If bFind = True Then
                Exit For
                Exit Function
            Else
                FindSecondNode(aTreeView, n, strFullPath)
            End If
        Next
    End Function

    ''' <summary>
    ''' 查詢下級TreeNode
    ''' </summary>
    ''' <param name="TV">需查詢的TreeView</param>
    ''' <param name="n">需查詢的TreeNode</param>
    ''' <param name="strFullPath">需查詢的TreeNode的FullPath</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function FindSecondNode(ByVal TV As TreeView, ByVal n As TreeNode, ByVal strFullPath As String) As Boolean

        Dim aNode As TreeNode
        For Each aNode In n.Nodes
            If aNode.FullPath = strFullPath Then
                TV.Focus()
                TV.SelectedNode = aNode

                Return True
                Exit For
                Exit Function
            Else
                FindSecondNode(TV, aNode, strFullPath)
            End If

        Next
    End Function

    Private Sub TVGoodsType_DoubleClick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TVGoodsType.DoubleClick
        Try
            If Me.TVGoodsType.SelectedNode IsNot Nothing Then
                'If Me.TVGoodsType.SelectedNode.GetNodeCount(False) > 0 Then
                '    MsgBox(GetMsg("BSC", "GoodsTypeNotDetail"), MsgBoxStyle.Information + MsgBoxStyle.OkOnly, Msg.CompanyName)
                '    Me.TVGoodsType.SelectedNode.ExpandAll()
                '    Exit Sub

                'End If
                Select Case selectObj.Name
                    Case "txtGoodsType"
                        Me.txtGoodsType.Text = Me.TVGoodsType.SelectedNode.FullPath
                        Me.txtGoodsType.Tag = Me.TVGoodsType.SelectedNode.Tag.ToString.Split("^")(0)
                        Me.Panel7.Visible = False

                End Select

            End If
        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub LoadGoodsCountInfo()

        Try
            Dim sql As String = ""
            m_Ds = New DataSet
            sql = "select Store,Replace(GoodsBarcode,'*','') as GoodsBarCode,sum(Goodsamount) as Goodsamount from "
            sql += " (select Store=case tradetype when '+' then isnull(a.ToStore,null) when '-' then isnull(a.FromStore,null) end,"
            sql += " b.GoodsBarCode, goodsamount=case tradetype when '+' then b.Goodsamount when '-' then (-1)* b.Goodsamount else 0 end "
            sql += " from Stor_TradeMaster a inner join Stor_TradeDetail b on a.bonum=b.bonum where BoStatus='B') a where 1=1 group by GoodsBarCode,Store"
            m_Ds = ReturnDataset(sql)
        Catch ex As Exception
            MsgBox("LoadGoodsCountInfo:", MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

    Private Sub SetToolTipInfo()

        ToolTip1.IsBalloon = True

        Dim ShowMsg As String = ""
        Me.ToolTip1.ToolTipTitle = "貨品名稱：" & Me.dgrdGoods.CurrentRow.Cells("Cnname").Value
        ShowMsg += "倉庫名" & Space(10) & "倉存量" & vbCrLf

        Dim CurrentBarCode As String = Me.dgrdGoods.CurrentRow.Cells("Barcode").Value

        Dim Rows() As DataRow = m_Ds.Tables(0).Select("GoodsBarCode='" & CurrentBarCode & "'")
        If Rows.Length > 0 Then
            For Each mRow As DataRow In Rows
                ShowMsg += mRow("Store") & Space(10) & mRow("Goodsamount") & vbCrLf
            Next
        End If
    End Sub

    Private Sub dgrdGoods_RowPostPaint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewRowPostPaintEventArgs) Handles dgrdGoods.RowPostPaint
        AddDgvRowNumber(dgrdGoods, sender, e)
    End Sub

    Private Sub dgrdGoods_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgrdGoods.CellContentClick

        Try

            Dim CurrentBarcode As String = Me.dgrdGoods.CurrentRow.Cells("Barcode").Value
            If Me.mIndex = 4 Then
                Dim Account As Decimal = CDec(Me.dgrdGoods.CurrentRow.Cells("FStoreQty").Value)
                If Account <= 0 Then
                    Exit Sub
                End If
            End If
            If CurrentBarcode.Length <= 0 Then
                Exit Sub
            End If
            LoadFirstTree(CurrentBarcode, mIndex)
            ShowPO()
            CountQty()
        Catch ex As Exception
            MsgBox("dgrdGoods_CellClick:" & ex.ToString, MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub

End Class